<template>
  <div class="container">
    <div>
      <el-card class="invoice-instructions mb-2">
        <div class="title">
          <h3>
            <i class="el-icon-info"></i>
            {{ $language.local("Notice") }}:
          </h3>
        </div>
        <ol class="info-body1">
          <li>工作内容描述不录入具体人员姓名、金额数字等详细内容；</li>
          <li>
            工作内容的描述不能有如下字眼：
            <em class="red">工资、补贴、津贴、福利、劳务、销售、经纪、工程安装、装修、装饰、清包工</em>
            等字眼；
          </li>
        </ol>
        <p>如有疑问请联系平台客服人员。</p>
      </el-card>
    </div>

    <el-form
      :disabled="isCheck"
      :model="formData"
      :rules="$rules"
      class="pr-2 pl-2 grid-flex"
      label-width="8rem"
      ref="taskInfoRef"
      status-icon
    >
      <el-form-item
        :label="$language.local('ServiceName')"
        prop="MID"
      >
        <select-id
          :apiName="`/api/Common/GetServiceProviderList`"
          label-key="ServiceName"
          v-model="formData.SID"
        ></select-id>
        <!-- <select-id
              v-model="formData.MID"
              label-key="MerchantName"
              :apiName="`/api/MerchantSign/GetList?status=1`"
        ></select-id>-->
      </el-form-item>
      <el-form-item
        :label="$language.local('customerName')"
        prop="MID"
      >
        <select-merchantid
          @change="midChange"
          v-model="formData.MID"
        ></select-merchantid>
        <!-- <select-id
              v-model="formData.MID"
              label-key="MerchantName"
              :apiName="`/api/MerchantSign/GetList?status=1`"
        ></select-id>-->
      </el-form-item>
      <el-form-item
        :label="$language.local('任务名称')"
        prop="projectName"
      >
        <xy-input
          clearable
          v-model="formData.projectName"
        ></xy-input>
      </el-form-item>
      <el-form-item
        :label="$language.local('TskType')"
        prop="TskType"
      >
        <select-servicetype
          :merchantId="formData.MID"
          :placeholder="$language.local('请选择') + $language.local('TskType')"
          v-model="formData.TskType"
        ></select-servicetype>
      </el-form-item>

      <el-form-item
        :label="$language.local('开始日期')"
        prop="BegTime"
      >
        <select-date v-model="formData.BegTime"></select-date>
      </el-form-item>
      <el-form-item
        :label="$language.local('结束日期')"
        :rules="EndTimeRule"
        prop="EndTime"
      >
        <select-date v-model="formData.EndTime"></select-date>
      </el-form-item>
      <el-form-item
        :label="$language.local('Amount')"
        prop="Amount"
      >
        <xy-decimal v-model="formData.Amount"></xy-decimal>
      </el-form-item>
      <el-form-item
        :label="$language.local('recruitPerson')"
        prop="recruitPerson"
      >
        <el-select
          :placeholder="`${$language.local('请选择')}${$language.local('recruitPerson')}`"
          v-model="formData.recruitPerson"
        >
          <el-option
            :key="item.value"
            :label="item.label"
            :value="item.value"
            v-for="item in recruitPersons"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item
        label="任务地区"
        prop="taskRegionC"
      >
        <xy-input v-model="formData.taskRegionC"></xy-input>
      </el-form-item>
      <el-form-item
        :label="$language.local('SettlementModes')"
        prop="SettlementModes"
      >
        <select-settlementmode v-model="formData.SettlementModes"></select-settlementmode>
      </el-form-item>
      <el-form-item
        label="其它结算方式"
        prop="otherSettlementModes"
        v-if="formData.SettlementModes == 4"
      >
        <xy-input v-model="formData.otherSettlementModes"></xy-input>
      </el-form-item>

      <el-form-item v-if="ServiceContents.length > 0">
        <el-select
          @change="ServiceContentChange"
          class="select-servicecontent"
          placeholder="可选择参考范例"
          v-model="ServiceContent"
        >
          <el-option
            :key="item.Id"
            :label="item.ModelTitle"
            :value="item"
            v-for="item in ServiceContents"
          ></el-option>
        </el-select>
      </el-form-item>

      <el-form-item
        :label="$language.local('工作内容')"
        class="textarea"
        prop="WorkContent"
      >
        <xy-input
          :autosize="{ minRows: 3 }"
          clearable
          type="textarea"
          v-model="formData.WorkContent"
        ></xy-input>
        <!-- <div class="info">工作内容描述不录入具体人员姓名、金额数字等详细内容；</div>
        <div class="info">
          工作内容的描述不能有如下字眼：
          <em class="red">工资、补贴、津贴、福利、劳务、销售、经纪、工程安装、装修、装饰、清包工</em>
          等字眼；
        </div>-->
      </el-form-item>
      <el-form-item
        :label="$language.local('RecruitmentRequirements')"
        class="textarea"
        prop="RecruitmentRequirements"
      >
        <xy-input
          :autosize="{ minRows: 3 }"
          clearable
          type="textarea"
          v-model="formData.RecruitmentRequirements"
        ></xy-input>
      </el-form-item>
      <el-form-item
        :label="$language.local('（可选）附件')"
        class="upload-file"
        prop="attFilePath"
      >
        <!-- <span class="info">(可选项) 关于任务的需求文档</span> -->
        <upload-file
          :name="formData.attFileName"
          :on-success="onSuccess"
          v-model="formData.attFilePath"
        ></upload-file>
      </el-form-item>
    </el-form>
    <div class="form-footer pb-3">
      <el-button
        @click="$router.go(-1)"
        size="mini"
      >
        {{
        $language.local("返回")
        }}
      </el-button>
      <template v-if="api.action == 'Check'">
        <el-button
          @click="showReasonDialog"
          class
          size="mini"
          type="danger"
        >{{ $language.local("不通过") }}</el-button>
        <el-button
          @click="onCheck(1)"
          size="mini"
          type="success"
        >
          {{
          $language.local("通过")
          }}
        </el-button>

        <!-- #region 审核原因 -->
        <el-dialog
          :title="$language.local('Reason')"
          :visible.sync="inputReasonVisible"
        >
          <el-form
            :model="formData"
            :rules="$rules"
            ref="ReasonRef"
            status-icon
          >
            <el-form-item prop="Reason">
              <xy-input
                clearable
                v-model="formData.Reason"
              ></xy-input>
            </el-form-item>
          </el-form>
          <div
            class="dialog-footer"
            slot="footer"
          >
            <el-button
              @click="onCheck(2)"
              size="mini"
              type="primary"
            >确 定</el-button>
          </div>
        </el-dialog>
        <!-- #endregion -->
      </template>
      <el-button
        @click="onSubmit('taskInfoRef')"
        size="mini"
        type="primary"
        v-else
      >{{ $language.local("确定") }}</el-button>
    </div>
  </div>
</template>

<script>
import API from "../../plugins/api";
export default {
  data() {
    const validateEndTime = (rule, value, callback) => {
      if (!this.formData.BegTime) {
        callback(new Error("请输入开始时间！"));
        return;
      }
      const begTime = new Date(this.formData.BegTime);
      const endTime = new Date(value);
      if (endTime.compare(begTime)) {
        callback();
      } else {
        callback(new Error("结束日期应大于开始日期！"));
      }
    };
    return {
      api: new API("/api/ServiceProject/Create"),
      merchant: null,
      id: "",
      formData: {
        MID: "",
        SID: "",
        ServiceType: "",
        TskType: "",
        PostName: "",
        projectName: "",
        recruitPerson: 1,

        WorkContent: "",
        PerformanceFeeSettlementRules: "",

        ServiceName: "",
        BegTime: new Date(),
        EndTime: new Date(),
        Amount: 500000,
        PayType: 1,
        attFileName: null,
        attFilePath: null,
        SettlementModes: 2,
        otherSettlementModes: "",
        RecruitmentRequirements: "",
        checker: "",
        checkstatus: "",
        taskRegionC: "",
        Reason: "",
      },
      attFileList: null,
      isCheck: false,
      inputReasonVisible: false,
      recruitPersons: [
        {
          value: 1,
          label: "1-5人"
        },
        {
          value: 2,
          label: "6-10人"
        },
        {
          value: 3,
          label: "11-20人"
        },
        {
          value: 4,
          label: "20人以上"
        }
      ],
      EndTimeRule: [
        { required: true, message: "不能为空", trigger: "blur" },
        { validator: validateEndTime, trigger: "blur" },
      ],
      ServiceContent: "",
      ServiceContents: [],
    };
  },
  watch: {
    "formData.TskType": {
      async handler(newValue) {
        try {
          const response = await this.$http.get(
            `/api/ServiceProject/GetContentModel?ServiceContent=${newValue}`
          );
          console.log(response);
          if(response.data.Data && response.data.Data.length > 0)
            this.ServiceContents = response.data.Data;
        } catch (error) {
          console.error(error);
        }
      },
    },
  },
  created(){
    this.formData.EndTime.setMonth(this.formData.EndTime.getMonth() + 1);
  },
  mounted() {
    this.onConfig();
  },
  methods: {
    async onConfig() {
      let { apiName, id } = this.$route.query;

      if (!apiName || !id) {
        return;
      }
      this.api = new API(apiName);
      this.id = id;
      if (this.api.action == "Check") {
        this.isCheck = true;
      }

      let item = null;
      try {
        item = await this.getServiceProjectById(id);
      } catch (error) {
        console.error(error);
        this.$router.replace("/ServiceProjectList");
        throw error;
      }
      if (!item) {
        console.log(123);
        this.$router.replace("/ServiceProjectList");
        return;
      }

      this.formData = {
        ...this.formData,
        MID: item.mid,
        ...item,
      };
    },
    async getServiceProjectById(id) {
      let response = await this.$http.get(`/api/ServiceProject/GetModel/${id}`);
      console.log(response);
      return response.data.Data;
    },
    onSuccess(e) {
      console.log(e);
      this.formData.attFileName = e.docname;
    },
    showReasonDialog() {
      this.inputReasonVisible = true;
    },
    async onCheck(check) {
      console.log(this.formData);
      if (check == 2) {
        await this.$refs["ReasonRef"].validate();
      }
      let response = await this.$http.post(
        `/api/ServiceProject/Check/${this.id}?checkstatus=${check}&Reason=${this.formData.Reason}`
      );
      console.log(response);
      this.$router.go(-1);
    },
    async onSubmit(formName) {

      console.log(this.formData);
      this.formData.ServiceType = this.formData.TskType;
      this.$refs[formName].validate(async (valided, err1) => {
        if (!valided) {
          let keys = Object.keys(err1);
          this.$message.error(
            this.$language.local(err1[keys[0]][0].field) +
              this.$language.local(err1[keys[0]][0].message)
          );
          return;
        }
        this.formData.BegTime = new Date(this.formData.BegTime).format("yyyy-MM-dd");
        this.formData.EndTime = new Date(this.formData.EndTime).format("yyyy-MM-dd");
        try {
          await this.$http.post(this.api.create, this.formData);

          // this.$message.success(response.data.Message);
          this.$router.go(-1);
        } catch (error) {
          console.error(error);
        }
      });
    },
    ServiceContentChange(e) {
      console.log(e);
      this.formData.WorkContent = e.ModelContent;
      this.formData.RecruitmentRequirements = e.RRContent;
    },
    midChange(e) {
      console.log(e);
      this.formData = {
        ...this.formData,
        taskRegionC: e.areaName,
        projectName: e.ProjectName,
        WorkContent: e.RequirementDescription,
        RecruitmentRequirements: e.TechnicalRequirement,

      };
      // this.formData.ProjectName = e.ProjectName;
      // this.formData.RequirementDescription = e.RequirementDescription;
      //  this.formData.TechnicalRequirement = e.TechnicalRequirement;
      console.log(this.formData);
    },
  },
};
</script>

<style lang="less" scoped>
.el-select {
  width: 100%;
}
.row {
  align-items: flex-start;
  width: 100%;
}
.select-servicecontent {
  color: gray;
}
.invoice-instructions {
  margin: 0;
  padding: 0 2rem;
  .info-body1 {
    //display: flex;
    //flex-wrap: wrap;

    li + li {
      margin-top: 1ex;
    }
  }
}
</style>
